import java.util.*;

public class Worker implements Runnable {

    private volatile boolean isRunning = true;
    private Thread thread;

    private ArrayList<String> lines = new ArrayList<String>();
    private Map<String, Integer> tmpWords = Collections.synchronizedMap(new TreeMap<String, Integer>());
    private Map<String, Integer> allWords;

    public void setThread(Thread thread) {
        this.thread = thread;
    }

    public Thread getThread() {
        return thread;
    }

    public void setAllWords(Map<String, Integer> words) {
        allWords = words;
    }

    public boolean isRunning() {
        return isRunning;
    }

    public void setRunning(boolean isRunning) {
        this.isRunning = isRunning;
    }

    public ArrayList<String> getLines() {
        return lines;
    }

    @Override
    public void run() {
        while (true) {
            if (isRunning) {
                tmpWords.clear();
                for (int j = 0; j < lines.size(); j++) {
                    String line = lines.get(j);
                    StringTokenizer tokenizer = new StringTokenizer(line, " \t\n\r,.:!?;'\"()[]{}");
                    while (tokenizer.hasMoreTokens()) {
                        String word = tokenizer.nextToken().toLowerCase();
                        CountWords.addWord(tmpWords, word, 1);
                    }
                }
                for (String word : tmpWords.keySet()) {
                    CountWords.addWord(allWords, word, tmpWords.get(word));
                }
                lines.clear();
                isRunning = false;
            }
            if (CountWords.isEndFileFlag()) {
                break;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
            }
        }
    }
}
